<template>
    <div>
        <div class="boderSet">
            <div class="top">
                <el-row>
                    <el-col :span="24">
                        <div class="grid-content bg-purple-dark">
                            <el-breadcrumb separator-class="el-icon-arrow-right">
                                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                                <el-breadcrumb-item>系统设置</el-breadcrumb-item>
                                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
                            </el-breadcrumb>
                        </div>
                    </el-col>
                </el-row>
            </div>
            <div class="content">
                <el-row>
                    <el-col :span="24">
                        <div class="conten-top">
                            <span>用户列表</span>
                        </div>
                    </el-col>
                </el-row>
                <!-- ------------------------------------------------------------------- -->
                <el-row>
                    <el-col :span="3">
                        <div class="btn-group">
                            <el-button type="primary" icon="el-icon-plus" style="padding: 12px;"
                                @click="handAddUser">添加用户</el-button>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div>
                            <el-input placeholder="请输入角色名称" v-model="input2">
                                <el-button slot="append" type="primary" @click="searchName()">查询</el-button>
                            </el-input>
                        </div>
                    </el-col>
                    <el-col :span="15">
                        <div class="btn-group" style="float: right;">
                                <el-button type="primary"
                                    style="background-color: white; color: #3F3F65; border-color: #3F3F65;"
                                    @click="exportExcel">导出Excel<i class="el-icon--right"></i>
                                </el-button>
                                   
                        </div>
                    </el-col>
                </el-row>
                <div class="struct-content">
                    <el-table ref="multipleTable" :data="getRoleList" cell-class-name="table-center" tooltip-effect="dark"
                        style="width: 100%" @selection-change="handleSelectionChange" id="selectTable">
                        <el-table-column type="selection" :cell-style="centeredCellStyle" width="100" :id="id"
                            header-align="center" align="center">
                        </el-table-column>
                        <el-table-column prop="name" :cell-style="centeredCellStyle" label="姓名" width="150"
                             header-align="center" align="center">
                        </el-table-column>
                        <el-table-column prop="username" :cell-style="centeredCellStyle" label="用户名" width="150"
                            header-align="center" align="center">
                        </el-table-column>
                        <el-table-column prop="departmentName" :cell-style="centeredCellStyle" label="所属部门" width="300"
                            header-align="center" align="center">
                        </el-table-column>
                        <el-table-column :cell-style="centeredCellStyle" label="角色"  header-align="center" align="center">
                            <template slot-scope="scope">
                                <span v-for="item in scope.row.roles"><el-tag type="success" style="margin-left: 5px;">{{
                                    item.roleName }}</el-tag> </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" :cell-style="centeredCellStyle" width="230" fixed="right"
                             header-align="center" align="center">
                            <template slot-scope="scope" :cell-style="centeredCellStyle">
                                <el-button size="mini" type="info" icon="el-icon-edit" @click="handEditUser(scope.row.id)"
                                    circle></el-button>
                                <el-tooltip content="部门配置" placement="top" effect="light" :hide-after="800"><el-button
                                        size="mini" type="warning" icon="el-icon-s-tools" circle
                                        @click="handDepartmentconfig(scope.row.id)"></el-button></el-tooltip>
                                <el-tooltip content="角色配置" placement="top" effect="light" :hide-after="800"> <el-button
                                        size="mini" type="warning" icon="el-icon-user-solid"
                                        @click="handRoleconfig(scope.row.roles, scope.row.id)"
                                        circle></el-button></el-tooltip>
                                <el-tooltip content="重置密码" placement="top" effect="light" :hide-after="800">
                                    <el-button size="mini" type="warning" icon="el-icon-refresh"
                                        @click="handResultPwd(scope.row.id, scope.row.name, scope.row.username)"
                                        circle></el-button></el-tooltip>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="handDelete(scope.row.id)"
                                    circle></el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                    <div class="pagination">
                        <el-pagination @current-change="handleCurrentChange" :current-page="currentPage"
                            :page-size="pageSize" :total="getTatol" background layout="prev, pager, next">
                        </el-pagination>
                    </div>
                </div>
            </div>
        </div>
        <!-- 模态框 -->
        <el-dialog :title="moduleTitle" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <!-- 添加修改 -->
            <div v-if="isAddUser">
                <el-form status-icon :rules="rules" :label-position="labelPosition" ref="formLabelAlign" label-width="80px"
                    :model="formLabelAlign">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="formLabelAlign.name"></el-input>
                    </el-form-item>
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="formLabelAlign.username"></el-input>
                    </el-form-item>
                    <el-form-item v-if="!isEditUser" label="密码" prop="pass">
                        <el-input type="password" v-model="formLabelAlign.pass"></el-input>
                    </el-form-item>
                    <el-form-item v-if="!isEditUser" label="确认密码" prop="checkPass">
                        <el-input type="password" v-model="formLabelAlign.checkPass"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 角色配置 -->
            <div v-if="isRoleUser">
                <span>当前角色为</span>
                <el-table row-key="id" :data="getAllRole" :tree-props="roleAlls" @selection-change="selectionRole"
                    node-key="id" ref="getAllRole">
                    <el-table-column type="selection" width="55">
                    </el-table-column>
                    <el-table-column prop="roleName" label="角色名称" align="center">
                    </el-table-column>
                </el-table>
            </div>
            <!-- 部门配置 -->
            <div v-if="isDepartmentconfig">
                <el-tree style=" border-radius: 10px; padding: 28px; margin-left: 15px;" :data="getDepartmentData"
                    :props="defaultProps" @node-click="handleNodeClick" :default-expand-all=true :show-checkbox="true"
                    :check-strictly="true" node-key="departmentName" @check="checkedBox" ref="tree"></el-tree>
            </div>
            <!-- 按钮 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="handCancel(formName)">取 消</el-button>
                <el-button type="primary" @click="handSubmit(formName)">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
import toExcel from "./../../utils/toExcel";
export default {
    name: 'userManagement',
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.formLabelAlign.checkPass !== '') {
                    this.$refs.formLabelAlign.validateField('checkPass');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.formLabelAlign.pass) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        var isUserNameNull = (rule, value, callback) => {
            if (value === "") {
                callback(new Error('请输入用户名'));
            } else {
                callback()
            }
        };
        var isNameNull = (rule, value, callback) => {
            if (value === "") {
                callback(new Error('请输入姓名'));
            } else {
                callback()
            }
        };
        return {
            types: ["success", "warning", "danger"],
            roleList: [], // 储存roleid的集合
            labelPosition: 'right',
            isAddUser: false, // 是否显示添加内容
            isRoleUser: false,// 显示角色配置模态框内容
            isEditUser: false,//显示修改的模态框内容
            isDepartmentconfig: false,// 显示是否显示部门配置
            dialogVisible: false,//判断模态框是否显示
            moduleTitle: '',//模态框显示的标题
            formName: '',//当前表单的名字
            defaultProps: {
                children: 'departmentVos',
                label: 'departmentName'
            },
            roleAlls: {
                label: "roleName"
            },
            formLabelAlign: {
                id: "",
                name: '',
                pass: '',
                checkPass: '',
                username: '',
                departmentName: '',
                roleName: '',
                treeNodeId: 0,
                did: 0
            },
            rules: {
                pass: [
                    { required: true, validator: validatePass, trigger: 'blur' }
                ],
                checkPass: [
                    { required: true, validator: validatePass2, trigger: 'blur' }
                ],
                username: [{ required: true, validator: isUserNameNull, trigger: 'blur' }],
                name: [{ validator: isNameNull, required: true, trigger: 'blur' }]
            },
            currentPage: 1,
            pageSize: 10,
            id: [],
            input2: "",
            selectData: [] // 需要打印的内容
        }
    },
    methods: {
        ...mapActions(["showDepartment", "queryUserAll", "userAdd", "userUpdate",
            "userById", "showDepartment", "updateDepartment", "roleAll", "userRole", "UserDelete"]),
        handDelete(id) {
            this.UserDelete(id)
            if (id == 1) {
                this.$message({
                    message: "不能删除最高权限管理员",
                    type: "error",
                    center: true
                })
                return
            }
            this.$confirm("确认删除这个角色嘛？").then(_ => {
                this.UserDelete(id).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: "删除成功",
                            type: "success",
                            center: true
                        })
                        this.queryUserAll({ limit: 10, name: this.input2, page: 1 })
                    }
                })
            })

        },
        selectionRole(id) {
            this.roleList = id
            console.log("list", id);
            console.log("Arr", this.roleList);
        },
        handleNodeClick(data) {
            console.log("in", data);
        },
        handleCurrentChange(currentPage) {//获取页码
            console.log(currentPage);
            this.currentPage = currentPage;
            setTimeout(() => { this.queryUserAll({ limit: this.pageSize, name: this.input2, page: this.currentPage }) }, 1000)

        },
        handleSelectionChange(id) { //获取选择的内容
            this.id = id;
            console.log("当前id", id);
        },
        centeredCellStyle() {
            return { textAlign: 'center' };
        },
        handleClose(done) { // 关闭模态框
            this.$confirm('确认关闭？')
                .then(_ => {
                    this.isAddUser = false
                    this.isEditUser = false
                    this.isDepartmentconfig = false
                    this.dialogVisible = false
                    this.isRoleUser = false
                    this.moduleTitle = '';
                    this.$refs[this.formName].resetFields();
                    done();
                })
                .catch(_ => { });
        },
        searchName() {//搜索
            this.queryUserAll({ limit: this.pageSize, name: this.input2, page: this.currentPage })
        },
        handRoleconfig(id, uid) { // 配置角色
            this.dialogVisible = true;
            this.moduleTitle = '角色配置'
            this.formName = 'formLabelAlign'
            this.isRoleUser = true
            this.formLabelAlign.id = uid
            console.log("id是", uid);
            let ids = id
            let newArr = [];
            console.log("allRole", this.getAllRole);
            for (let index = 0; index < ids.length; index++) {
                console.log("ids", ids[index].roleName);
                newArr.push(ids[index].roleName);
                console.log("newarr", newArr);
            }
            for (const key in this.getAllRole) {
                let i = -1
                for (const keys in newArr) {
                    if (this.getAllRole[key].roleName == newArr[keys]) {
                        console.log("id", this.getAllRole[key].roleName, "newarr", newArr[keys]);
                        i = key
                        console.log("i", i);
                        setTimeout(() => {
                            this.$refs.getAllRole.toggleRowSelection(this.getAllRole[i], true)
                        })
                        break;
                    }
                }


            }

        },
        handSubmit(formName) { // 提交按钮
            console.log(formName);
            console.log("test", this.isAddUser, this.isEditUser);
            if (this.isAddUser || this.isEditUser) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(valid);
                        if (this.isAddUser && !this.isEditUser) {//添加
                            console.log("in");
                            this.userAdd({
                                name: this.formLabelAlign.name,
                                password: this.formLabelAlign.pass,
                                username: this.formLabelAlign.username
                            }).then(res => {
                                if (res.code == 200) {
                                    this.$message({
                                        message: '添加成功',
                                        type: 'success'
                                    });
                                    this.isAddUser = false
                                    this.dialogVisible = false
                                    this.queryUserAll({ limit: this.pageSize, name: this.input2, page: this.currentPage })
                                    this.$refs[formName].resetFields();
                                }
                            })


                        }
                        if (this.isEditUser) {//修改
                            this.userUpdate({
                                name: this.formLabelAlign.name,
                                password: this.formLabelAlign.pass,
                                username: this.formLabelAlign.username,
                                id: this.formLabelAlign.id,
                            }).then(res => {
                                if (res.code == 200) {
                                    this.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    });
                                    this.$refs[formName].resetFields();
                                    this.queryUserAll({ limit: this.pageSize, name: this.input2, page: this.currentPage })
                                    this.isAddUser = false
                                    this.isEditUser = false
                                    this.dialogVisible = false
                                    this.moduleTitle = ''
                                }
                            })


                            this.isDepartmentconfig = false
                            this.dialogVisible = false
                            this.isRoleUser = false
                            this.moduleTitle = ''
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
            if (this.isDepartmentconfig) {//部门配置
                console.log("did", this.formLabelAlign.did, "uid", this.formLabelAlign.id);
                this.updateDepartment({ did: this.formLabelAlign.did, uid: this.formLabelAlign.id }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: '部门配置成功',
                            type: 'success'
                        });
                        this.queryUserAll({ limit: this.pageSize, name: this.input2, page: this.currentPage })
                        this.isDepartmentconfig = false
                        this.dialogVisible = false
                    }
                })
            };
            if (this.isRoleUser) {//角色配置
                let rid = [];
                for (const key in this.roleList) {
                    rid.push(this.roleList[key].id)
                }
                console.log("rid", rid);
                this.userRole({ rid, uid: this.formLabelAlign.id }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            message: '角色配置成功',
                            type: 'success'
                        });
                    }
                    this.isRoleUser = false
                    this.dialogVisible = false
                    this.queryUserAll({ limit: this.pageSize, name: this.input2, page: this.currentPage })
                })

            }
        },
        handDepartmentconfig(id) { // 部门配置按钮
            this.dialogVisible = true;
            this.moduleTitle = '部门配置'
            this.formName = 'formLabelAlign'
            this.isDepartmentconfig = true;
            this.formLabelAlign.id = id
            this.userById(id).then(res => {
                this.formLabelAlign.departmentName = res.department
                this.$refs.tree.setCheckedKeys([this.formLabelAlign.departmentName], true)
            })

        },
        handAddUser() { //控制添加角色显示内容
            this.dialogVisible = true;
            this.moduleTitle = '添加角色'
            this.formName = 'formLabelAlign'
            this.isAddUser = true;
        },
        handEditUser(id) { //控制修改角色显示内容
            this.dialogVisible = true;
            this.moduleTitle = '修改角色'
            this.isAddUser = true;
            this.formName = 'formLabelAlign'
            this.isEditUser = true;
            console.log(id);
            this.userById(id).then(res => {
                console.log("is list", res);
                this.formLabelAlign.name = res.name
                this.formLabelAlign.username = res.username
                this.formLabelAlign.id = res.id
            })

        },
        handCancel(formName) {//取消按钮
            this.isAddUser = false
            this.isEditUser = false
            this.isDepartmentconfig = false
            this.dialogVisible = false
            this.isRoleUser = false
            this.moduleTitle = '';
            if (this.isAddUser || this.isEditUser) {
                this.$refs[formName].resetFields();
            }



        },
        handResultPwd(id, name, username) {//重置密码
            console.log(id, name, username);
            this.$confirm('确认重置密码？').then(() => {
                this.userUpdate({
                    name: name,
                    password: "123456",
                    username: username,
                    id: id,
                }).then(res => {
                    console.log(this.formLabelAlign.name);
                    console.log('res', res);
                    if (res.code == 200) {
                        this.$message({
                            message: '密码重置成功',
                            type: 'success',
                            center: true
                        });
                    }
                })
            }).catch(() => {
                this.$message({
                    message: '取消密码重置',
                    type: 'warning',
                    center: true
                });
            })


        },
        checkedBox() { // 获取选择的数据
            let checkData = this.$refs.tree.getCheckedNodes().concat(this.$refs.tree.getHalfCheckedNodes());
            for (var i in checkData) {
                // 判断子节点是否存在子节点 如果存在直接请求并且提示 false
                if (!checkData[i].hasOwnProperty("children")) {
                    // 判断是否只选择一个 如果存在直接请求并且提示 false
                    if (checkData.length == 1) {
                        console.log(checkData[0].id)
                    } else {
                        this.$message.error("只选择一个节点");
                        this.$refs.tree.setCheckedKeys([]);
                        return
                    }
                } else {
                    this.$message.error("只能选择当前分类最后的子分类");
                    this.$refs.tree.setCheckedKeys([]);
                    return
                }
            }
            console.log(checkData);
            let id = 0
            for (let i = 0; i < checkData.length; i++) {
                id = checkData[i].id
            }
            this.formLabelAlign.did = id
            console.log('选择的id', this.formLabelAlign.did);

        },
        exportExcel() { // 导出 数据    
            if (this.id.length < 1) {
                this.$message({
                    message: "请选择需要导出的内容",
                    type: "error",
                    center: true
                })
                return false
            }
            toExcel.getExcel("#selectTable", "用户表数据")
        }

    },
    created() {
        this.queryUserAll({ limit: 10, name: this.input2, page: 1 })
        this.getTatol
        this.getUserUpdateList
        this.showDepartment()
        this.roleAll({ limit: 10, nsme: "", page: 1 })
        this.getAllRole
        console.log("10", this.getRoleList);
    },
    computed: {
        ...mapGetters(["getRoleList", "getTatol", "getUserUpdateList", "getDepartmentData", "getAllRole"])
    }

}
</script>
<style scoped>
.top {
    padding: 10px 20px 5px 29px;
    align-items: middle;
}

.conten-top {
    padding: 0 32px 0 40px;
}

.boderSet {
    margin: 0 29px;
    /* margin: 29px; */
    border-radius: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 30px;
}

.btn-group {
    padding-left: 40px;
}

.struct-content {
    margin-top: 10px;
    width: 100%;
    min-height: 400px;
    border-top: 1px solid rgb(212, 209, 209);
    margin-bottom: 20px;
}

.table-center {
    text-align: center !important;
}

.pagination {
    margin-top: 10px;
    float: right;
    margin-bottom: 10px;
}

::v-deep .el-input-group {
    line-height: normal;
    display: inline-table;
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    margin-left: 10px;
}

::v-deep .el-input-group__append button.el-button {
    border-color: #00000000;
    background-color: #343961;
    color: white;
    border-top: 0;
    border-bottom: 0;
}
</style>
